#include "ui_draw.h"

namespace UI{

KTV_Draw* KTV_Draw::p_draw = NULL;
KTV_Draw* KTV_Draw::Create(string path){
	if(NULL == p_draw){
		p_draw = new KTV_Draw(path);
	}
	return p_draw;
}
KTV_Draw::KTV_Draw(string path){
	this->font_path = path;
	this->font_size = 12;
	this->font_style = TTF_STYLE_NORMAL;
	this->p_font = NULL;
}
KTV_Draw::~KTV_Draw(){
	if(this->p_font){
		TTF_CloseFont(this->p_font);
		this->p_font = NULL;
	}
	p_draw = NULL;
}
bool KTV_Draw::Initial(){
	if(this->p_font == NULL){
		this->p_font = TTF_OpenFont(this->font_path.c_str(),this->font_size);
		if(this->p_font == NULL){
			cerr<< "Open font error: " << TTF_GetError() << endl;
			return false;
		}
		TTF_SetFontStyle(this->p_font,this->font_style);
	}
	return true;
}
bool KTV_Draw::changeFontSize(int size){
	if(size != this->font_size){
		this->font_size = size;
		TTF_CloseFont(this->p_font);
		this->p_font = TTF_OpenFont(this->font_path.c_str(),size);
	}
	return true;
}
SDL_Surface*  KTV_Draw::DrawUTF8_Blend(const string& text,UI_Color color,int size,int style) {
	this->changeFontSize(size);
	if(style != this->font_style){
		this->font_style = style;
		TTF_SetFontStyle(this->p_font,this->font_style);
	}
	return TTF_RenderUTF8_Blended(this->p_font,text.c_str(),color.ToSDLColor());
}
SDL_Surface*  KTV_Draw::DrawUTF8_Solid(const string& text,UI_Color color,int size,int style) {
	this->changeFontSize(size);
	if(style != this->font_style){
		this->font_style = style;
		TTF_SetFontStyle(this->p_font,this->font_style);
	}
	return TTF_RenderUTF8_Solid(this->p_font,text.c_str(),color.ToSDLColor());
}
SDL_Surface*  KTV_Draw::DrawUTF8_Shaded(const string& text,UI_Color fg,UI_Color bg,int size,int style) {
	this->changeFontSize(size);
	if(style != this->font_style){
		this->font_style = style;
		TTF_SetFontStyle(this->p_font,this->font_style);
	}
	return TTF_RenderUTF8_Shaded(this->p_font,text.c_str(),fg.ToSDLColor(),bg.ToSDLColor());
}

SDL_Surface* KTV_Draw::GetFromImageFile(const string& file){
		SDL_Surface* image = IMG_Load(file.c_str());
		if(image == NULL){
			cerr<< "Load image " << file << " error: " << SDL_GetError() << endl;
			return NULL;
		}
		if(SDL_SetAlpha(image,SDL_SRCALPHA|SDL_RLEACCEL,255)){
			cerr << "set alpha error:" << SDL_GetError() << endl;
			SDL_FreeSurface(image);
			return NULL;
		}
		SDL_Surface* s = SDL_DisplayFormatAlpha(image);
		if(s == NULL){
			cerr << "get surface on SDL_DisplayFormatAlpha error: " << SDL_GetError() << endl;
		}
		SDL_FreeSurface(image);
		return s;
}

}

